package com.quanyan.ic.datacenter.email;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * Created by zhuo.shi on 2017/8/23.
 */
@Component
public class MailServiceImpl implements MailService {

    private static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Value("${mail.fromMail.address}")
    private String defaultFromMailAddress;

    @Autowired
    private JavaMailSender mailSender;


    @Override
    public void sendSimpleMail(String from, String to, String subject, String content) {
        String[] toList = StringUtils.split(to, ",");
        for (String t : toList) {
            if (StringUtils.isEmpty(t)){
                continue;
            }
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(t);
            message.setSubject(subject);
            message.setText(content);
            try {
                mailSender.send(message);
                logger.info("send mail: from [{}] to [{}] OK", from, t);
            } catch (Exception e) {
                logger.error("send mail: from [{}] to [{}] Error: {}", from, t, e.getMessage());
            }
        }
    }

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        sendSimpleMail(defaultFromMailAddress, to, subject, content);
    }

    @Override
    public void sendHtmlMail(String from, String to, String subject, String content) {

    }

    @Override
    public void sendAttachmentsMail(String from, String to, String subject, String content, List<File> attachments) {

    }
}
